<?php
/**
 * Created by PhpStorm.
 * User: zjw
 * Date: 2018/3/29
 * Time: 上午11:40
 */

namespace backend\models;

use common\models\BindPhone;
use common\models\CouponCategory;
use common\models\User;
use common\models\UserCoupon;
use yii\data\ActiveDataProvider;
use yii\db\ActiveQuery;

/**
 *
 * @property ActiveQuery $query
 */
class BindPhoneSearch extends BindPhone
{
    public $status;
    public $startTime;
    public $endTime;
    public $query;
    public $item_id;
    public $phone;
    public $attempt;
    public $catalog;

    public function rules()
    {
        return [
            [['status', 'item_id', 'catalog'], 'integer'],
            [['startTime', 'endTime', 'phone'], 'string']
        ];
    }


    public function search($params)
    {
        $this->query = BindPhone::find();
        $dataProvider = new ActiveDataProvider([
            'query' => $this->query
        ]);
        if (!$this->load($params)) {
            return $dataProvider;
        }

        if (isset($this->startTime) && $this->startTime !== '') {
            $this->setStartTime();
        }

        if (isset($this->catalog) && $this->catalog !== '') {
            $this->setCatalog();
        }

        if (isset($this->endTime) && $this->endTime !== '') {
            $this->setEndTime();
        }

        if (isset($this->item_id) && $this->item_id !== '') {
            $this->setItemId();
        }
        if (isset($this->phone) && $this->phone !== '') {
            $this->setPhone();
        }

        if (isset($this->status) && $this->status !== '') {
            $this->setStatus();
        }

        return $dataProvider;
    }

    private function setStartTime()
    {
        $this->query->andWhere(['>', 'updated_at', strtotime($this->startTime)]);
    }

    private function setEndTime()
    {
        $this->query->andWhere(['<', 'updated_at', strtotime($this->endTime)]);
    }

    public function setItemId()
    {
        $this->query->andWhere(['item_id' => $this->item_id]);
    }

    public function setPhone()
    {
        $this->query->andWhere(['phone' => $this->phone]);
    }

    public function setCatalog()
    {
        $category = CouponCategory::findOne($this->catalog);
        $this->query->andWhere(['item_id' => $category->group_id]);
    }

    public function setStatus()
    {
        $this->query->andWhere(['status' => $this->status]);
    }
}
